package cn.edu.swu.wn.io;

import java.util.Scanner;

public class Main {
    private static Scanner scanner = new Scanner(System.in);
    private static ImageManager imageManager = new ImageManager();

    public static void main(String[] args) {
        System.out.println("=== 图片下载系统 ===");
        boolean running = true;

        while (running) {
            printMenu();
            int choice = getUserChoice();

            switch (choice) {
                case 1:
                    downloadImageMenu();
                    break;
                case 2:
                    imageManager.listImages();
                    break;
                case 3:
                    searchImageMenu();
                    break;
                case 4:
                    running = false;
                    System.out.println("感谢使用，再见！");
                    break;
                default:
                    System.out.println("无效的选项，请重新输入");
            }

            // 等待用户按回车继续
            if (running) {
                System.out.println("\n按回车键继续...");
                scanner.nextLine(); // 消耗之前的换行符
                scanner.nextLine(); // 等待用户输入
                clearScreen();
            }
        }

        scanner.close();
    }

    private static void printMenu() {
        System.out.println("\n请选择操作:");
        System.out.println("1. 下载图片");
        System.out.println("2. 查看所有图片");
        System.out.println("3. 搜索图片");
        System.out.println("4. 退出");
        System.out.print("请输入选项 (1-4): ");
    }

    private static int getUserChoice() {
        try {
            return Integer.parseInt(scanner.nextLine().trim());
        } catch (NumberFormatException e) {
            return -1;
        }
    }

    private static void downloadImageMenu() {
        System.out.print("请输入图片URL: ");
        String url = scanner.nextLine().trim();

        if (url.isEmpty()) {
            System.out.println("URL不能为空");
            return;
        }

        imageManager.downloadImage(url);
    }

    private static void searchImageMenu() {
        System.out.print("请输入要搜索的图片名称: ");
        String name = scanner.nextLine().trim();

        if (name.isEmpty()) {
            System.out.println("搜索名称不能为空");
            return;
        }

        imageManager.searchImage(name);
    }

    // 简单的清屏操作，在不同系统可能效果不同
    private static void clearScreen() {
        try {
            if (System.getProperty("os.name").contains("Windows")) {
                new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
            } else {
                System.out.print("\033[H\033[2J");
                System.out.flush();
            }
        } catch (Exception e) {
            // 清屏失败不做处理
        }
    }
}
